/**
 * ----------------------------------------------------
 * Monitoring GUI Scripts
 * ----------------------------------------------------
 * @author PoLuX
 */
jQuery(function($){
	jQuery.extend({
    	/**
    	 * Monitoring instanced object
    	 */
    	Monitoring: ( function()
        { 
    		/**
    		 * Class attributes
    		 */
    		var	 tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";
    		var	 tabCounter = 2;
    		var  CurrentCultureID = null;
    		
    		/**
    		 * Refresh Culture combobox
    		 *
    		 * @see callback
    		 * @param string data	Donn�es renvoy�es
    		 */
    		function _cb_refreshSelectCulture(data, textStatus, jqXHR)
    		{
    			if(data.code == "OK")
    			{
    				//var OptSelect = $('#slctCulture option:selected').val();
    				
    				$("#slctCulture option").remove();
    				$('#slctCulture').append('<option value="0" selected="selected"><I>Choisir</I></option>');
    				for (var i=0; i<data.data.length; i++) {
    					$('#slctCulture').append(new Option(data.data[i]['CULT_LIB']+" - "+data.data[i]['TECHCULT_CODE'],data.data[i]['CULT_CODE'],false,false)); //;'<option value="'+data.data[i]['CULT_CODE']+'">'+data.data[i]['CULT_LIB']+" - "+data.data[i]['TECHCULT_CODE']+'</option>');
    				}       
    				$('#slctCulture').val(CurrentCultureID);
    				$('#slctCulture').bind("change",function(){
    					$.Monitoring.refreshCultureData($('#slctCulture option:selected').val());
    				});
    			}
    			else
    				alert(msgs);
    		}
    		/**
    		 * Refresh Sensors indicators
    		 *
    		 * @see callback
    		 * @param string data	Donn�es renvoy�es
    		 */
    		function _cb_refreshSensorsValues(data, textStatus, jqXHR)
    		{
    			// Gestion du type de message
    			if(data.code == "OK")
    			{
    				$.Monitoring.refreshTemperature(data.data['AR_TEMPEDC']);
    				$.Monitoring.refreshPressure(data.data['AR_PRESSION']);
    				$.Monitoring.refreshHum(data.data['AR_HUMIDITY']);
    				$.Monitoring.refreshLum(data.data['AR_LUMINOSITY']);
    				//$("#txtEnvTemperature").val(data.data['AR_TEMPEDC']+" \xB0C");
    				//$("#txtEnvPressure").val(data.data['AR_PRESSION']+" hPa");
//    				$("#txtEnvHumidity").val(data.data['AR_HUMIDITY']+" %");
//    				$("#txtEnvLuminosity").val(data.data['AR_LUMINOSITY']+" lums");
//        				       
    				
    				// TODEV -> bind event on all options to refresh main Tab
    			}
    			else
    				alert(msgs);
    		}
    		/**
    		 * Refresh Culture Data
    		 *
    		 * @see callback
    		 * @param string data	Donn�es renvoy�es
    		 */
    		function _cb_statutCulture(data, textStatus, jqXHR)
    		{
    			// Gestion du type de message
    			if(data.code == "OK")
    			{
    				try{
	    				$("#spanTitreCulture")
	    					.html(data.data[0]['LIB']+" - <I>"+data.data[0]['TECHCULT']+"</I>");
	    				$("#spanNbJoursCultureDepuisDeb")
	    					.html(data.data[0]['NB_J_DEB_CULT']+"j/"+data.data[0]['NB_J_FIN_CULT']+"j")
	    					.attr('title','Total: '+(eval(parseInt(data.data[0]['NB_J_DEB_CULT'])+parseInt(data.data[0]['NB_J_FIN_CULT']))).toString()+"j");
	    				$("#spanPhaseCourante")
	    					.html("<B>Phase "+data.data[0]['PHCULT_LIB']+" </B>")
	    					.attr('title',data.data[0]['PHCULT_CODE']);
	    				CurrentCultureID = data.data[0]['CODE'];
    				}
    				catch(except)
    				{
    					alert("Exception during JS script :"+except.message);
    				}
	    		}
	    		else
	    				alert(data.msgs);
    					$('#slctCulture').val(CurrentCultureID);
	    		}
    		
    		/**
             * Class public Methods
             */
            return {
            	
            	/**
            	 * 
            	 * @returns
            	 */
            	refreshCultureData:function(p_s_CultureID)
            	{
            		var serviceName = "statutCulture";
                	var formatValue = "json";
                	
                	var dataToSend = {
                			service : serviceName,
                			format : formatValue ,
                			cult : p_s_CultureID
                    };
                	
                	$.post("index.php", dataToSend,_cb_statutCulture, "json" );
            	},
            	/**
            	 * Refresh Temprature values
            	 */
            	refreshTemperature : function(p_d_temp)
            	{
            		var progressbar = $( "#tempProgressBar" );
            		var progressbarValue = progressbar.find( ".ui-progressbar-value" );
            		var colorProgressBar;
            		
            		// Upper part of Page
            		$("#txtEnvTemperature").val(parseFloat(p_d_temp)+" \xB0C");
            		$("#tempValueStatus").html(parseFloat(p_d_temp)+" \xB0C");
            		
            		
            		// ProgressBar and indicator
            		// TO DEV TODO Gestion multi Culture - Multi Arduino
            		
            		progressbar.progressbar("option",{value: parseFloat(p_d_temp)});
            		
            		// Green bar by default
            		colorProgressBar = "#18BC10";
            		
            		// Downer then 18,0°C => cold blue
            		if(parseFloat(p_d_temp)<18.0)
            			colorProgressBar = "#2DF5FC";
            		// Between 18,0°C and 24,0°C => green
            		if(parseFloat(p_d_temp)>=18.0)
            			colorProgressBar = "#18BC10";
            		// Between 24,0°C and 27,0°C => Orange
            		if(parseFloat(p_d_temp)>=24.0)
            			colorProgressBar = "#FCD32D";
            		// Upper then 27,0°C => Red
            		if(parseFloat(p_d_temp)>=27.0)
            			colorProgressBar = "#F92A0E";
            			
            		// Color management
            		progressbarValue.css({
            			 "background": colorProgressBar
            			 });            		
            	},
            	/**
            	 * Refresh Pressure values
            	 */
            	refreshPressure : function(p_d_pressure)
            	{
            		// Upper part of Page
            		$("#txtEnvPressure").val(parseFloat(p_d_pressure)+" hPa");
            		$("#pressureValueStatus").html(parseFloat(p_d_pressure)+" hPa");
            		
            	},
            	/**
            	 * Refresh Humidity values
            	 */
            	refreshHum : function(p_d_Hum)
            	{
            		// Upper part of Page
            		$("#txtEnvHumidity").val(parseInt(p_d_Hum)+" %");
            		$("#HumValueStatus").html(parseInt(p_d_Hum)+" %");            		
            	},
            	/**
            	 * Refresh Luminosity values
            	 */
            	refreshLum : function(p_d_lum)
            	{
            		// Upper part of Page
            		$("#txtEnvLuminosity").val(parseFloat(p_d_lum)+" lums");
            		$("#LumValueStatus").html(parseFloat(p_d_lum)+" lums");
            		
            		if(parseFloat(p_d_lum)<100.0)
            		{
            			$("#imgStatutCulture").addClass("ui-perso-moon");
            		}
            		else
            			$("#imgStatutCulture").addClass("ui-perso-sunshine");
            		
            	},
                /**
                 * Refresh Select List of Culture
                 */
                refreshSelectCulture : function()
                {
                	var serviceName = "lstCulture";
                	var formatValue = "json";
                	
                	CurrentCultureID = $('#slctCulture option:selected').val();
                	
                	var dataToSend = {
                			service : serviceName,
                			format : formatValue 
                    };
                	
                	$.post("index.php", dataToSend,_cb_refreshSelectCulture, "json" );
                },
               
                /**
                 * Refresh Select List of Culture
                 */
                refreshSensorsValues : function()
                {
                	var serviceName = "lastArduinoReport";
                	var formatValue = "json";
                	
                	var dataToSend = {
                			service : serviceName,
                			format : formatValue 
                    };
                	$.post("index.php", dataToSend,_cb_refreshSensorsValues, "json" );
                },
                /**
                 * Initialize User Interface objects
                 */
                initUI: function()
                {
                	//alert("Init UI - Starting");
                	// $( "#olSensors" ).selectable();
                	
//                	 $("#menu").menu({
//                		 select: function(event,ui){
//                			 $.Monitoring.addTab("test","test");
//                		 }
//                	 }); 
                	
                	$.Monitoring.refreshSelectCulture();
                	 $("#btnRefreshArduinoReport").button();
                	 
                	 $("#divAccordion").accordion();
                	 $("#btnRefreshingDataAboutCulture").button({
                		 icons: {
                			 primary: "ui-icon-refresh"
                			 },
                			 text: false
                	 });
                	 $( document ).tooltip();
                	 
                	 
                	 $("#btnRefreshingDataAboutCulture").bind("click",function (event){$.Monitoring.refreshCultureData(CurrentCultureID);});
                	 
                	 $("#btnRefreshArduinoReport").bind("click",function (event){$.Monitoring.refreshSensorsValues();}); 
                	 $("#tempProgressBar").progressbar({
                		 value: false,
                		 max : 40.0
                	 });
                }
                
//                initMonitoringTabs:function()
//                {
//                	 $("#divMonitoringTabs").tabs({ collapsible: false });
//                	 $("#divMonitoringTabs").tabs( "option", "heightStyle", "auto");
//                	 
//                	 // close icon: removing the tab on click
//                	 $("#divMonitoringTabs").delegate( 
//                			 "span.ui-icon-close", 
//                			 "click", 
//                			 function() {
//                				 var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
//                				 $( "#" + panelId ).remove();
//                				 $("#divMonitoringTabs").tabs( "refresh" );
//                			 });
//                	 
//                	 $("#divMonitoringTabs").bind( 
//                			 "keyup", 
//                			 function( event ) {
//                				 if ( event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE ) {
//                					 var panelId = $("#divMonitoringTabs").find( ".ui-tabs-active" ).remove().attr( "aria-controls" );
//                					 $( "#" + panelId ).remove();
//                					 $("#divMonitoringTabs").tabs( "refresh" );
//                				 }
//                			 });
//                	 
//                	 $.Monitoring.addTab("Main","Salut initialization dynamique !!!");
//                	 $("#divMonitoringTabs").tabs( "refresh" );
//                	 
//                	 
//                },
//                
//                addTab:function(p_s_newTabName,p_s_content){
//                	
//                	
//                	
////                    	 var tabs = $( "#tabs" ).tabs();
////                    	 // modal dialog init: custom buttons and a "close" callback reseting the form inside
////                    	
////                    	
////                    	 // actual addTab function: adds new tab using the input from the form above
////                    	 function addTab() {
//                	 var label = p_s_newTabName || "Tab " + tabCounter,
//                	 id = "tabs-" + tabCounter,
//                	 li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
//                	 tabContentHtml = p_s_content || "Tab " + tabCounter + " content.";
//                	 $("#divMonitoringTabs").find( ".ui-tabs-nav" ).append( li );
//                	 $("#divMonitoringTabs").append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
//                	 $("#divMonitoringTabs").tabs( "refresh" );
//                	 tabCounter++;
//                	 
////                    	 // addTab button: just opens the dialog
////                    	 $( "#add_tab" )
////                    	 .button()
////                    	 .click(function() {
////                    	 dialog.dialog( "open" );
////                    	 });
////                    	 // close icon: removing the tab on click
////                    	 tabs.delegate( "span.ui-icon-close", "click", function() {
////                    	 var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
////                    	 $( "#" + panelId ).remove();
////                    	 tabs.tabs( "refresh" );
////                    	 });
////                    	 tabs.bind( "keyup", function( event ) {
////                    	 if ( event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE ) {
////                    	 var panelId = tabs.find( ".ui-tabs-active" ).remove().attr( "aria-controls" );
////                    	 $( "#" + panelId ).remove();
////                    	 tabs.tabs( "refresh" );
////                    	 }
////                    	 });
////                    	 });
//                }
            }
        })()
    });
    
    /**
     * Starting Client object
     */
    $.Monitoring.initUI();
});